<template>
  <basic-container>
    <div v-show="serviceType.serviceType">
      <div class="headerFont" v-if="serviceType.serviceType" >{{serviceType.serviceTypeName}}</div>
      <!-- <div class="headerFont" v-if="serviceType.serviceType==2" >{{serviceType.serviceTypeName}}</div> -->
      <div class="c_card">
        <div class="c_card_item">
          <div class="c_card_label">钱包余额</div>
          <el-card class="box-card">
            <div class="b_money">{{accountData.totalBalance || 0}} 元</div>
            <div class="b_typeBox">
              <div class="bt_box">
                <div class="bt_money">{{accountData.balanceMay || 0}} 元</div>
                <div class="bt_txt">可提</div>
              </div>
              <div class="bt_line"></div>
              <div class="bt_box">
                <div class="bt_money">{{accountData.payable || 0}} 元</div>
                <div class="bt_txt">欠款</div>
              </div>
            </div>
            <div class="c_btn1">
              <el-button class="btn" v-show="accountData.isWithdraw == '1'" @click="setTakeOutShow">去提现</el-button>
            </div>
          </el-card>
        </div>
        <div class="c_card_item" v-if="serviceType.serviceType!=0">
          <div class="c_card_label">发票管理</div>
          <el-card class="box-card">
            <div class="b_money">{{accountData.limit || 0}} 元</div>
            <div class="b_typeBox">
              <div class="bt_box">
                <div class="bt_money">{{accountData.opened || 0}} 元</div>
                <div class="bt_txt">待开</div>
              </div>
              <div class="bt_line"></div>
              <div class="bt_box">
                <div class="bt_money">{{accountData.trial || 0}} 元</div>
                <div class="bt_txt">待审</div>
              </div>
            </div>
            <div class="c_btn1">
              <el-button class="btn" @click="goToInvoice('去开票')">去开票</el-button>
            </div>
          </el-card>
        </div>
        <div class="c_card_item" v-if="serviceType.serviceType==0">
          <div class="c_card_label">累计提现</div>
          <el-card class="box-card">
            <div class="b_money" style="margin-top:52px;">{{accountData.cumulative || 0}} 元</div>
          </el-card>
        </div>
      </div>
    </div>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
    <!-- 
      @row-update="rowUpdate"               编辑数据后确定触发该事件
      @row-save="rowSave"                   新增数据后点击确定触发该事件
      @row-del="rowDel"                     行数据删除时触发该事件
      @search-change="searchChange"         击搜索后触发该事件(由于page分页信息和search搜索信息是sync修饰符，可以直接通过this.page和this.search拿到)
      @search-reset="searchReset"           清空搜索回调方法
      @selection-change="selectionChange"   当选择项发生变化时会触发该事件
      @current-change="currentChange"       分页页码改变时会触发
      @size-change="sizeChange"             pageSize改变时会触发 
      @refresh-change="refreshChange"       点击刷新按钮触发该事件(由于page分页信息和search搜索信息是sync修饰符，可以直接通过this.page和this.search拿到)
      @sort-change="sortChange"             当表格的排序条件发生变化的时候会触发该事件
      @on-load="onLoad"                   
     -->
    </avue-crud>
    <!-- 提现 -->
    <el-dialog
      title="提现"
      append-to-body
      :visible.sync="takeOutShow"
      :close-on-click-modal="false"
      ref="takeOut_dialog"
      v-if="takeOutShow"
      width="500px"
      :before-close="beforeClose_takeOut"
    >
        <div class="box_form" v-loading="takeOutLoading"  element-loading-text="加载中...">
          <div class="haruyuki-flex-space-between ">
              <div class="form_money">提现到：{{takeOutFrom.data.bank.robBank}}</div>
              <div class="takeOutAll" @click="selectBank = true">选择</div>
            </div>
          <el-form ref="takeOutFrom" :rules="rules" :label-position="'top'" status-icon label-width="80px" :model="takeOutFrom">
            <el-form-item label="提现金额" prop='paymoeny'>
              <el-input-number v-model="takeOutFrom.paymoeny" @change="queryTrueBalance(takeOutFrom.paymoeny)" :min="0" class="inputNumber" placeholder="请输入提现金额" size="small" :precision="2" />
            </el-form-item>
            <!-- <div class="takeOutAll" @click="takeOutAll">全部提现</div> -->
            <div class="haruyuki-flex-space-between ">
              <div class="form_money">可提金额：{{accountData.balanceMay}}</div>
              <div class="takeOutAll" @click="takeOutAll">全部提现</div>
            </div>
          </el-form>

          <div class="form_money">服务费扣除 <span v-show="takeOutFrom.data.rate">({{takeOutFrom.data.rate}})</span> ：{{takeOutFrom.data.rateFee || 0}}元</div>
          <div class="form_money">转账费扣除/笔：{{takeOutFrom.data.onceFee || 0}}元</div>
          <div class="form_money">发票额度扣除：{{takeOutFrom.data.invoiceLimit || 0}}元</div>
          <div class="form_money">实际到账金额：{{takeOutFrom.data.trueAmount || 0}}元</div>
          <div class="rembit">
            <!-- <div class="form_money" v-show="takeOutFrom.data.note1">说明：<span class="coloy">{{takeOutFrom.data.note1}}</span></div>
            <div class="form_money" v-show="takeOutFrom.data.note2">说明：<span class="coloy">{{takeOutFrom.data.note2}}</span></div>
            <div class="form_money" v-show="takeOutFrom.data.note3">说明：<span class="coloy">{{takeOutFrom.data.note3}}</span></div>
            <div class="form_money" v-show="takeOutFrom.data.note4">说明：<span class="coloy">{{takeOutFrom.data.note4}}</span></div> -->

            <div class="form_money" v-show="takeOutFrom.data.note3">
              <div>说明：</div>
              <div class="coloy">{{takeOutFrom.data.note1}}  </br> {{takeOutFrom.data.note2}}  </br> {{takeOutFrom.data.note3}} </br> {{takeOutFrom.data.note4}}</div>
            </div>

          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" v-show="visiblePopover" @click="submitRules">申请提现</el-button>
        </span>
    </el-dialog>
    <!-- 选择银行 -->
    <el-dialog
      title="选择银行卡"
      append-to-body
      :visible.sync="selectBank"
      :close-on-click-modal="false"
      ref="takeOut_dialog"
      v-if="selectBank"
      width="555px"
    >
     <div class="bankWrap">
        <div class="form_money">开户行：{{takeOutFrom.data.bank.robBank}}</div>
        <div class="form_money">账户名：{{takeOutFrom.data.bank.robBankName}}</div>
        <div class="form_money">账户号：{{takeOutFrom.data.bank.robBankNo}}</div>
     </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,getAccountInfo,queryBalanceAmount,postWithdraw
} from "@/api/rb-service/oemWithdrawal/oem_withdrawal";
import { mapGetters } from "vuex";
// import { getToken } from "@/util/auth";
export default {
  data() {
    var validatePaymoeny = (rule, value, callback) => {
      if (!value) {
        callback(new Error(`请输入提现金额（不少于${this.takeOutFrom.data.withdrawLimit}元）`));
      } else if (value < this.takeOutFrom.data.withdrawLimit) {
        callback(new Error(`请输入提现金额（不少于${this.takeOutFrom.data.withdrawLimit}元）`));
      } else if (value > this.accountData.balanceMay) {
        callback(new Error('您的可提现金额没有这么多！'));
      } else {
        callback();
      }
    };
    return {
      accountData:{},
      serviceType:{},//serviceType|serviceTypeName---	类型(2一般纳税人、1小规模、0个人)
      form: {},
      query: {},
      search: {},
      loading: true,
      takeOutLoading:false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        addBtn:false,
        viewBtn: true,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        editBtn:false,// 编辑按钮
        delBtn:false,// 删除
        // menuWidth:150,       //操作栏宽度
        // labelWidth:120,      //弹出表单的标题的统一宽度
        searchLabelWidth: 120, //搜索框标题宽度
        column: [
          {
            label: "开户名称",//
            prop: "robBankName",
            type: "input",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入开户名称",
                trigger: "blur",
              },
            ],
            overHidden: true
          },
          {
            label: "开户行",
            prop: "robBank",//
            type: "input",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入开户行",
                trigger: "blur",
              },
            ],
            overHidden: true
          },
          {
            label: "账户类型",//
            prop: "accountType",
            type: "select",
            search: true,
            rules: [
              {
                required: true,
                message: "请选择账户类型",
                trigger: "blur",
              },
            ],
            dataType: 'number',
            dicUrl: "/api/blade-system/dict/dictionary?code=account_type",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true
          },
          {
            label: "转账类型",//
            prop: "forwardType",
            type: "select",
            search: true,
            rules: [
              {
                required: true,
                message: "请选择转账类型",
                trigger: "blur",
              },
            ],
            dataType: 'number',
            dicUrl: "/api/blade-system/dict/dictionary?code=forward_type",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
            minWidth:100
          },
          {
            label: "提现金额",
            prop: "rowMoney",//
            type: "input",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入提现金额",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "提现状态",//
            prop: "rowStatus",
            type:'select',
            search: true,
            rules: [
              {
                required: true,
                message: "请选择提现状态",
                trigger: "blur",
              },
            ],
            dataType: 'number',
            dicUrl: "/api/blade-system/dict/dictionary?code=row_status",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
            minWidth:100
          },
          {
            label: "提现日期",//
            search: false,
            prop: "withdrawDate",
            type: "datetime",
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd hh:mm:ss',
            valueFormat:'yyyy-MM-dd hh:mm:ss',
            rules: [
              {
                required: true,
                message: "请输入提现日期",
                trigger: "blur",
              },
            ],
            width: 140,
            overHidden: true
          },
          {
            label: "审核日期",//
            prop: "adminDate",
            type: "datetime",
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd hh:mm:ss',
            valueFormat:'yyyy-MM-dd hh:mm:ss',
            search: false,
            rules: [
              {
                required: true,
                message: "请选择审核日期",
                trigger: "blur",
              },
            ],
            width: 140,
            overHidden: true
          },
          {
            label: "到账日期",//
            prop: "notifyDate",
            type: "datetime",
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd hh:mm:ss',
            valueFormat:'yyyy-MM-dd hh:mm:ss',
            search: false,
            rules: [
              {
                required: true,
                message: "请选择到账日期",
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth:140
          },
          {
            search: true,
            label: "提现日期时间段",
            type: 'datetimerange',
            prop:'withdrawDateTime',
            searchRange: true,
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd HH:mm:ss',
            valueFormat:'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '提现日期时间开始时间',
            endPlaceholder: '提现日期时间结束时间',
            hide:true,
            display:false,
            overHidden: true
          },
          {
            search: true,
            label: "审核日期时间段",
            type: 'datetimerange',
            prop:'adminDateTime',
            searchRange: true,
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd HH:mm:ss',
            valueFormat:'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '审核日期时间开始时间',
            endPlaceholder: '审核日期时间结束时间',
            hide:true,
            display:false,
            overHidden: true
          },
          {
            search: true,
            label: "到账日期时间段",
            type: 'datetimerange',
            prop:'notifyDateTime',
            searchRange: true,
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd HH:mm:ss',
            valueFormat:'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '到账日期时间开始时间',
            endPlaceholder: '到账日期时间结束时间',
            hide:true,
            display:false,
            overHidden: true
          },
          {
            label: "审核意见",//
            prop: "robReason",
            type: "textarea",
            search: false,
            overHidden: true,
            minWidth:140
          }
        ],
      },
      data: [],
      takeOutShow:false,
      takeOutFrom:{},
      rules: {
        paymoeny: [
          { validator: validatePaymoeny, trigger: ['blur','change'] }
        ]
      },
      visiblePopover:true,
      selectBank:false
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.oem_withdrawal_add, false),
        viewBtn: this.vaildData(this.permission.oem_withdrawal_view, false),
        delBtn: this.vaildData(this.permission.oem_withdrawal_delete, false),
        editBtn: this.vaildData(this.permission.oem_withdrawal_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created(){
    this.AccountInfo()
  },
  methods: {
    // 打开去提现弹框
    setTakeOutShow(){
      queryBalanceAmount().then((res)=>{
        const data = res.data.data;
        this.takeOutFrom.data = data;
        // this.$refs['takeOutFrom'].clearValidate();
        this.takeOutShow=true;
        this.$forceUpdate();
      })
    },
    // 获取卡片 信息
    AccountInfo(){
      getAccountInfo().then((res)=>{
        this.accountData=res.data.data;
        if(JSON.stringify(this.accountData)==="{}"){
          this.$message.error(res.data.msg);
        }else{
          let {serviceType, serviceTypeName} = this.accountData;
          this.serviceType={serviceType, serviceTypeName};
        }        
      })
    },
    // 输入提现金额---查询提现数据
    queryTrueBalance(value){
      queryBalanceAmount(value).then((res)=>{
        const data = res.data.data;
        this.takeOutFrom.data = data;
        this.$refs['takeOutFrom'].clearValidate();
        this.$forceUpdate();
      })
    },
    
    // 全部提现
    takeOutAll(){
      this.takeOutFrom.paymoeny=this.accountData.balanceMay;
      queryBalanceAmount(this.takeOutFrom.paymoeny).then((res)=>{
        const data = res.data.data;
        this.takeOutFrom.data = data;
        this.$refs['takeOutFrom'].clearValidate();

        this.$forceUpdate();
      })
    },
    // 提现关闭回调
    beforeClose_takeOut(done){
      this.takeOutFrom={};
      this.takeOutLoading=false;
      done();
    },
    // 提现表单校验
    submitRules(){
      this.$refs['takeOutFrom'].validate((valid) => {
        if (valid) {
          this.submitTakeOutFrom();
        }
      });
    },
    // 提现表单--提交
    submitTakeOutFrom() { 
      let that = this;
      this.takeOutLoading=true;
      this.visiblePopover=false;
      postWithdraw(this.takeOutFrom.paymoeny).then( res =>{
        console.log(res.data.data)
        let data = res.data.data;
        that.takeOutLoading=false;
        that.visiblePopover=true;

        if(JSON.stringify(data) =="{}"){
          // 正常提现
          that.$message({
            type: "success",
            message: "操作成功!"
          });

          that.takeOutFrom={};
          that.takeOutShow=false;
          that.refreshChange();
          that.AccountInfo();
        }else{
          const h = this.$createElement;
          this.$msgbox({
            title: '温馨提示',
            message: h('p', null , [
              
              h('b', null, '请于提现时间段发起提现：'),
              h('p', { style: 'color: #E6A23C' }, data.daysRange),
              h('p', { style: 'color: #E6A23C' }, data.timeRange)
            ]),
            center: true,
            confirmButtonText: '确定',
            beforeClose: (action, instance, done) => {
              done();
            }
          })
        }
      }).catch(() =>{
        this.takeOutLoading=false;
        this.visiblePopover=true;
      })
    },
    goToInvoice(urlType){
      if(urlType == '去开票'){
        // this.$router.push({ path: '/rb-service/invoice/invoice' })//发票管理
        this.$router.push({ path: '/rb-service/invoiceMail/invoice_mail' })//发票邮寄记录
      }else if(urlType == '去确认'){
        this.$router.push({ path: '/rb-service/oemprofit/service_profit_month' })
        // this.$message.success('跳转到月分润页面')
      }
    },
    // handleDelete() {},
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        // getDetail(this.form.id).then((res) => {
        //   this.form = res.data.data;
        // });
      }
      done();
    },
    // 清空搜索回调方法
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    // 击搜索后触发该事件(由于page分页信息和search搜索信息是sync修饰符，可以直接通过this.page和this.search拿到)
    searchChange(params, done) {
      // 提现
      if(params.withdrawDateTime){
        params.beginWithdrawDate = params.withdrawDateTime[0];
        params.endWithdrawDate = params.withdrawDateTime[1];
      }
      // 审核
      if(params.adminDateTime){
        params.beginAdminDate = params.adminDateTime[0];
        params.endAdminDate = params.adminDateTime[1];
      }
      
      // 打款
      if(params.notifyDateTime){
        params.beginNotifyDate = params.notifyDateTime[1];
        params.endNotifyDate = params.notifyDateTime[1];
      }
      
      this.query = params;
      this.page.currentPage = 1;
      
      this.onLoad(this.page, params);
      done();
    },
    // 当选择项发生变化时会触发该事件
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    // 分页页码改变时会触发
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    // pageSize改变时会触发 
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    // 点击刷新按钮触发该事件(由于page分页信息和search搜索信息是sync修饰符，可以直接通过this.page和this.search拿到)
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query, {pageType:'0'})
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
        this.$forceUpdate()
      });
    },
    // 当表格的排序条件发生变化的时候会触发该事件
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
.headerFont{
  font-size: 36px;
  margin-bottom: 10px;
  color: #000;
}
.c_card{
  display: flex;
  margin-bottom: 32px;
  .c_card_item{
    margin-right: 16px;
    .c_card_label{
      height: 24px;
      font-size: 16px;
      font-family: Source Han Sans CN-Medium, Source Han Sans CN;
      font-weight: 500;
      line-height: 24px;
      color: #000;
      margin-bottom: 8px;
    }
    .box-card /deep/ .el-card__body{
      width: 288px;
      height: 216px;
      padding: 16px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      .b_money{
        margin-top: 16px;
        font-weight: 500;
        color: #000000;
        line-height: 36px;
        font-size: 26px;
        text-align: center;
        
        overflow: hidden;
      }
      .box_box{
        .box_money{
          height: 20px;
          font-size: 14px;
          font-family: Source Han Sans CN-Regular, Source Han Sans CN;
          color: #000000;
          line-height: 20px;
          text-align: center;
        }
        .box_txt{
          height: 20px;
          font-size: 14px;
          font-family: Source Han Sans CN-Regular, Source Han Sans CN;
          color: #000000;
          line-height: 20px;
          margin-top: 10px;
          text-align: center;

          overflow: hidden;
        }
      }
      .b_typeBox{
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .bt_line{
          width: 1px;
          height: 28px;
          border-left: #000 solid 1px;
        }
        .bt_box{
          width: 128px;
          .bt_money{
            height: 20px;
            font-size: 14px;
            font-family: Source Han Sans CN-Regular, Source Han Sans CN;
            color: #000000;
            line-height: 20px;
            text-align: center;
          }
          .bt_txt{
            height: 20px;
            font-size: 14px;
            font-family: Source Han Sans CN-Regular, Source Han Sans CN;
            color: #000000;
            line-height: 20px;
            text-align: center;
            margin-top: 10px;

            overflow: hidden;
          }

          
        }

      }
      .c_btn2{
        width: 100%;
        display: flex;
        justify-content: space-between;
        .btn{
          width: 120px;
        }
      }
      .c_btn1 .btn{
          width: 256px;
      }
    }
  }
}

.datail{
  padding-left: 141px;
  height: 20px;
  font-size: 14px;
  font-family: Source Han Sans CN-Regular, Source Han Sans CN;
  color: #000000;
  line-height: 20px;
  margin-bottom: 16px;
}

// .box_form{
//   // width: 280px;
//   // margin: auto;
// }
.form_money{
  // height: 20px;
  font-size: 14px;
  font-family: Source Han Sans CN-Regular, Source Han Sans CN;
  
  color: #000000;
  line-height: 20px;
  margin-bottom: 16px;
}
/deep/ .el-form-item__label{
  color: #000;
  font-weight: 500;
}
.el-form--label-top /deep/ .el-form-item__label{
  padding: 0;
}
.takeOutAll{
  height: 20px;
  font-size: 14px;
  font-weight: 500;
  color: #155BD4;
  cursor: pointer;
  text-align: right;
  // margin-top: -18px;
}
/deep/ .el-input-number__decrease,/deep/ .el-input-number__increase{
  display: none;
}
.inputNumber /deep/ .el-input__inner{
  padding-left: 15px;
  padding-right: 15px;
  width: 280px;
  text-align: left;
}

.dialog-footer{
  display: flex;
  justify-content: center;
}
.coloy{
  color: #f9831efa;
  padding-left: 10px;
}
.bankWrap{
    border: 1px solid #ccc;
    border-radius: 16px;
    box-shadow: 4px 3px 6px 0px;
    padding: 16px 16px 0 16px;
    margin: 0 20px 10px;
}
</style>
